﻿$.fn.localResizeIMG = function (obj) {
    this.on('change', function () {
        var file = this.files[0];
        var URL = window.URL || window.webkitURL;
        var blob = URL.createObjectURL(file);
        if ($.isFunction(obj.before)) {
            obj.before(this, blob, file)
        };
        _create(blob, file);
        this.value = '';
    });
    function _create(blob, file) {
        if (file.type.indexOf("image") >= 0) {
            var img = new Image();
            img.src = blob;
            img.onload = function () {
                var that = this;
                var w = that.width, h = that.height, scale = w / h;// w = obj.width || w; h = w / scale;
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                $(canvas).attr({ width: w, height: h });
                ctx.drawImage(that, 0, 0, w, h);
                var base64 = canvas.toDataURL('image/jpeg', obj.quality || 0.8);
                if (navigator.userAgent.match(/iphone/i)) {
                    var mpImg = new MegaPixImage(img);
                    mpImg.render(canvas, { maxWidth: w, maxHeight: h, quality: obj.quality || 0.8 });
                    base64 = canvas.toDataURL('image/jpeg', obj.quality || 0.8);
                }
                if (navigator.userAgent.match(/Android/i)) {
                    var encoder = new JPEGEncoder();
                    base64 = encoder.encode(ctx.getImageData(0, 0, w, h), obj.quality * 100 || 80);
                }
                var result = {
                    base64: base64,
                    clearBase64: base64.substr(base64.indexOf(',') + 1),
                    oldPic: img,
                    imgBlob: file,
                    type: "image"
                };
                obj.success(result);
            };
        }
        else if (file.type.indexOf("video") >= 0) {
            let _video = document.createElement('video');
            _video.className = "video_look";
            _video.src = blob;
            _video.currentTime = 1;
            _video.setAttribute("name", "fileVideo");

            _video.addEventListener("canplay", function (_event) {
                var canvas = document.createElement("canvas");
                canvas.width = _video.videoWidth;
                canvas.height = _video.videoHeight;
                canvas.getContext('2d').drawImage(_video, 0, 0, canvas.width, canvas.height);
                var img = document.createElement("img");
                img.src = canvas.toDataURL("image/png");

                var imgObj = new Image();
                imgObj.src = img.src;
                imgObj.onload = function () {
                    var that = this;
                    var w = that.width, h = that.height, scale = w / h; w = img.width || w; h = w / scale;
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    $(canvas).attr({ width: w, height: h });
                    ctx.drawImage(that, 0, 0, w, h);
                    var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8);
                    if (navigator.userAgent.match(/iphone/i)) {
                        var mpImg = new MegaPixImage(imgObj);
                        mpImg.render(canvas, { maxWidth: w, maxHeight: h, quality: 1 || 0.8 });
                        base64 = canvas.toDataURL('image/jpeg', obj.quality || 0.8);
                    }
                    if (navigator.userAgent.match(/Android/i)) {
                        var encoder = new JPEGEncoder();
                        base64 = encoder.encode(ctx.getImageData(0, 0, w, h), obj.quality * 100 || 80);
                    }
                    var result = {
                        base64: base64,
                        clearBase64: base64.substr(base64.indexOf(',') + 1),
                        videoObj: _video,
                        videoBlob: file,
                        type: "video"
                    };
                    obj.success(result);
                };
            });
        }
    }
};

/*************************************************************************************************************************
 ******************************************************  page logic  *****************************************************
 *************************************************************************************************************************/
$(document).ready(function () {
    //字数限制500字
    var lenInput = $('.textarea-item').val().length;
    $(".textarea-item").keyup(function () {
        lenInput = $(this).val().length;
        if (lenInput > 0 && lenInput <= 300) {
            $('.textareaInput').html(lenInput);
            $('.textarea-btn').attr('disabled', false);
        } else {
            $('.textarea-btn').attr('disabled', true);
        }
    });
    var _imgTypes = GetQueryString("imgTypes");
    $("#imgTypes").val(_imgTypes);
});

//获取URL参数值
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

var layer;
var showPicArr = new Array(), dbPicArr = new Array(), showVideo = new Array(), dbVideo = new Array(), videoSize = new Array();
$('input:file').localResizeIMG({
    width: 800,
    quality: 1,// 图片压缩 默认1 不压缩
    success: function (result) {
        var upFileIndex = layer.load();
        if (result.type == "image") {
            var img = new Image();
            img.src = result.base64;
            var _str = "<span class='pic_look' style='background-image: url(" + img.src + ")'><em id='delete_pic' data-type='img'></em></span>";
            $('#chose_pic_btn').before(_str);

            if (result != undefined) {
                var _len = showPicArr.length;
                showPicArr[_len] = {
                    strImg: result.base64,
                    size: result.imgBlob.size,
                    type: result.imgBlob.type
                };
            }
        } else if (result.type == "video") {
            var _str = "<span class='video_look' style='background-image: url(" + result.base64 + ")'><em id='delete_pic' data-type='video'></em></span>";
            $("#upload-video").before(_str);

            var _len = showVideo.length;
            //showVideo[_len] = result.base64;           

            //记录原始视频
            var video = result.videoBlob;
            videoSize[videoSize.length] = video;
            showVideo[_len] = {
                strVideo: "",
                imgVideo: result.base64,//视频图片
                size: result.videoBlob.size,
                type: result.videoBlob.type
            };

            var initSize = $("#hidVideoSize").val();
            $("#hidVideoSize").val(video.size + parseInt(initSize));

            var reader = new FileReader();
            reader.readAsDataURL(video);
            reader.onload = (e) => {
                var videoSrc = e.target.result;
                showVideo[_len].strVideo = videoSrc;
                dbVideo[dbVideo.length] = videoSrc;
            }
        }
        layer.close(upFileIndex);
    }
});

// 删除已选择的图片
$(document).on('click', '#delete_pic', function (event) {
    var _type = $(this).attr("data-type");
    if (_type === "img") {
        //获取被移除图片的索引
        var _index = $(this).parents(".pic_look").index();
        //移除显示图片组
        showPicArr.splice(_index, 1);
        //移除界面图片元素
        $(this).parents(".pic_look").remove();
    }
    else if (_type === "video") {
        //获取被移除图片的索引
        var _index = $(this).parents(".video_look").index();
        //移除显示图片组
        showVideo.splice(_index, 1);
        //移除DB图片组
        dbVideo.splice(_index, 1);
        var _video = videoSize[_index];
        var _initSize = $("#hidVideoSize").val();
        $("#hidVideoSize").val(parseInt(_initSize) - _video.size);
        videoSize.splice(_index, 1);
        //移除界面图片元素
        $(this).parents(".video_look").remove();
    }
});

layui.config({ base: '/themes/js/modules/' }).use(['element', 'layer', 'jquery', 'common', 'form', 'upload'], function () {
    var form = layui.form, $ = layui.jquery, os = layui.common, upload = layui.upload, layer = layui.layer;
    //监听提交
    form.on('submit(formSub)', function (data) {
        var tipstr = "快递单号不能为空！";
        if ($("#ImgTypes").val() == "1") tipstr = "样品抽检单号不能为空！";
        if (data.field.expressNo == undefined || data.field.expressNo.length == 0) { layer.msg(tipstr, { icon: 7 }); return false; }
        if (typeof (showPicArr) == "undefined" && typeof (showVideo) == "undefined") { layer.msg("请上传样品资源文件信息！", { icon: 7 }); return false; }
        if (showPicArr.length == 0 && showVideo.length == 0) { layer.msg("请上传样品资源文件信息！", { icon: 7 }); return false; }
        var m = {
            description: "",
            PicArr: showPicArr,
            VideoArr: showVideo,
            ExpressNo: data.field.expressNo,
            Types: $("#imgTypes").val() != undefined && $("#imgTypes").val().length != 0 ? parseInt($("#imgTypes").val()) : 0
        };
        var urls = "api/h5/submitForm";
        m.description = data.field.description;
        m.ImgSize = parseInt(videoSize);
        var upFileIndex = layer.load();
        try {
            os.ajax(urls, m, function (res) {
                layer.close(upFileIndex);
                if (res.statusCode == 200) {
                    layer.msg("上传成功！", { icon: 1 });
                    setTimeout(function () { window.location.href = '/H5Page/mine'; }, 1000);
                } else if (res.statusCode == 403) {
                    os.error("用户数据已过期！");
                    setTimeout(function () { window.location.href = '/H5Page/login'; }, 1000);
                }
                else {
                    layer.msg(res.message, { icon: 7 });
                }
            }, "post", function (xhr, type, errorThrown) {
                layer.close(upFileIndex);
                if (type === "timeout") {
                    layer.msg("连接超时，请稍后重试！", { icon: 7 });
                } else if (type === "error") {
                    layer.msg("连接异常，请稍后重试！", { icon: 7 });
                }
            });
            return false;
        } catch (e) {
            layer.close(upFileIndex);
            layer.msg(e.message, { icon: 7 });
        }
    });
});   